import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../res/color_res.dart';
import '../../../routes/app_pages.dart';
import '../controllers/home_controller.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('首页'),
        centerTitle: true,
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0.5,
      ),
      body: Container(
        color: const Color(pageBg),
        child: Column(
          children: [
            // 搜索框
            _buildSearchBar(),

            // 内容区域
            Expanded(
              child: RefreshIndicator(
                onRefresh: controller.refreshData,
                child: Obx(() {
                  if (controller.isLoading.value &&
                      controller.homeList.isEmpty) {
                    // 首次加载显示loading
                    return const Center(
                      child: CircularProgressIndicator(),
                    );
                  }

                  if (controller.homeList.isEmpty) {
                    // 空状态
                    return ListView(
                      children: [
                        SizedBox(height: 100.w),
                        Center(
                          child: Column(
                            children: [
                              Icon(
                                controller.searchKeyword.value.isEmpty
                                    ? Icons.article_outlined
                                    : Icons.search_off_outlined,
                                size: 80.w,
                                color: Colors.grey[400],
                              ),
                              SizedBox(height: 16.w),
                              Text(
                                controller.searchKeyword.value.isEmpty
                                    ? '暂无文章'
                                    : '未找到相关文章',
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: Colors.grey[600],
                                ),
                              ),
                              if (controller.searchKeyword.value.isNotEmpty)
                                Padding(
                                  padding: EdgeInsets.only(top: 8.w),
                                  child: Text(
                                    '搜索关键词: "${controller.searchKeyword.value}"',
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Colors.grey[500],
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                      ],
                    );
                  }

                  // 有数据时显示列表
                  return ListView.builder(
                    physics: const BouncingScrollPhysics(),
                    padding: EdgeInsets.all(16.w),
                    itemCount: controller.homeList.length,
                    itemBuilder: (context, index) {
                      final item = controller.homeList[index];
                      return _buildListItem(item);
                    },
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildListItem(item) {
    return InkWell(
      onTap: () {
        // 跳转到文章详情页
        Get.toNamed(
          Routes.HOME_DETAIL,
          arguments: {
            'postId': item.id,
          },
        );
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 16.w),
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.r),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.1),
              spreadRadius: 1,
              blurRadius: 3,
              offset: const Offset(0, 1),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 标题
            Text(
              item.title ?? '',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black87,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            SizedBox(height: 8.w),

            // 内容
            Text(
              item.content ?? '',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[600],
                height: 1.4,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),
            SizedBox(height: 12.w),

            // 底部信息
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _formatTime(item.createTime ?? ''),
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[500],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.w),
                  decoration: BoxDecoration(
                    color: item.state == 1
                        ? Colors.green.withOpacity(0.1)
                        : Colors.grey.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    item.state == 1 ? '已发布' : '草稿',
                    style: TextStyle(
                      fontSize: 10.sp,
                      color: item.state == 1 ? Colors.green : Colors.grey,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  String _formatTime(String timeStr) {
    try {
      final dateTime = DateTime.parse(timeStr);
      final now = DateTime.now();
      final difference = now.difference(dateTime);

      if (difference.inDays > 0) {
        return '${difference.inDays}天前';
      } else if (difference.inHours > 0) {
        return '${difference.inHours}小时前';
      } else if (difference.inMinutes > 0) {
        return '${difference.inMinutes}分钟前';
      } else {
        return '刚刚';
      }
    } catch (e) {
      return timeStr;
    }
  }

  // 构建搜索栏
  Widget _buildSearchBar() {
    return Container(
      padding: EdgeInsets.fromLTRB(16.w, 16.w, 16.w, 8.w),
      color: Colors.white,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[100],
          borderRadius: BorderRadius.circular(25.r),
        ),
        child: Row(
          children: [
            // 搜索图标
            Padding(
              padding: EdgeInsets.only(left: 16.w),
              child: Icon(
                Icons.search,
                color: Colors.grey[500],
                size: 20.sp,
              ),
            ),

            // 搜索输入框
            Expanded(
              child: TextField(
                controller: controller.searchController,
                decoration: InputDecoration(
                  hintText: '搜索文章标题...',
                  hintStyle: TextStyle(
                    color: Colors.grey[500],
                    fontSize: 14.sp,
                  ),
                  border: InputBorder.none,
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 12.w,
                  ),
                ),
                style: TextStyle(fontSize: 14.sp),
                textInputAction: TextInputAction.search,
                onSubmitted: (value) => controller.searchArticles(),
                onChanged: controller.onSearchChanged,
              ),
            ),

            // 清空按钮
            Obx(() => controller.searchText.value.isNotEmpty
                ? IconButton(
                    onPressed: controller.clearSearch,
                    icon: Icon(
                      Icons.clear,
                      color: Colors.grey[500],
                      size: 18.sp,
                    ),
                    padding: EdgeInsets.all(8.w),
                    constraints: BoxConstraints(
                      minWidth: 32.w,
                      minHeight: 32.w,
                    ),
                  )
                : SizedBox(width: 8.w)),
          ],
        ),
      ),
    );
  }
}
